package com.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.UUID;
import java.util.concurrent.Semaphore;

/**
 * Created by frinder on 2017/6/21.
 */
public class WkhtmltopdfHelper {


    static Logger logger = LoggerFactory.getLogger(ItextHtml2PdfHelper.class);

    public static void main(String[] args) {
        String tmpFileName = UUID.randomUUID().toString();
        String htmlUrl = "E:\\test\\fds.html";
        String pdfFilePath = "e:\\test\\" + tmpFileName + ".pdf";

        try {
             pdfTest(htmlUrl, pdfFilePath);
//            convert(htmlUrl, pdfFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


//    public static boolean convert(String srcPath, String destPath) {
//        File file = new File(destPath);
//        File parent = file.getParentFile();
//        //如果pdf保存路径不存在，则创建路径
//        if (!parent.exists()) {
//            parent.mkdirs();
//        }
//        String toPdfTool = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
//        StringBuilder cmd = new StringBuilder();
//        cmd.append(toPdfTool);
//        cmd.append(" ");
//        cmd.append(" --encoding").append(" utf8 ");
//        cmd.append(srcPath);
//        cmd.append(" ");
//        cmd.append(destPath);
//
//        boolean result = true;
//        try {
//            Process proc = Runtime.getRuntime().exec(cmd.toString());
//            HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
//            HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
//            error.start();
//            output.start();
//            proc.waitFor();
//        } catch (Exception e) {
//            result = false;
//            e.printStackTrace();
//        }
//
//        return result;
//    }
//
//
//    public static class HtmlToPdfInterceptor extends Thread {
//        private InputStream is;
//
//        public HtmlToPdfInterceptor(InputStream is) {
//            this.is = is;
//        }
//
//        public void run() {
//            try {
//                InputStreamReader isr = new InputStreamReader(is, "utf-8");
//                BufferedReader br = new BufferedReader(isr);
//                String line;
//                while ((line = br.readLine()) != null) {
//                    System.out.println(line.toString()); //输出内容
//                }
//            } catch (IOException e) {
//                logger.error(e.getMessage(), e);
//            }
//        }
//    }


    public static void pdfTest(final String htmlUrl, final String pdfFilePath) {
        // 只能5个线程同时访问
        final Semaphore semaphore = new Semaphore(2);
        final String whktmlExe = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
        try {
            // 获取许可
            semaphore.acquire();
            new Thread() {
                public void run() {
                    try {
                        ProcessBuilder pb = new ProcessBuilder(whktmlExe, "--print-media-type", "--margin-left", "10mm", "--margin-right", "10mm", "--encoding", "UTF-8", htmlUrl, pdfFilePath); // 使用print样式
                        pb.redirectErrorStream(true);
                        Process process = pb.start();
                        BufferedReader errStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf-8"));
                        String line = errStreamReader.readLine();
                        while (line != null) {
                            logger.info(line);
                            line = errStreamReader.readLine();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        semaphore.release();
                    }
                }
            }.start();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

}
